#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Docker健康检查脚本
检查OCR API服务的健康状态，包括营业执照识别功能
"""

import requests
import sys
import json
import time
import logging
from typing import Dict, Any

# 配置日志
logging.basicConfig(level=logging.INFO)
logger = logging.getLogger(__name__)


def check_api_health(base_url: str = "http://localhost:8002") -> Dict[str, Any]:
    """
    检查API健康状态
    
    Args:
        base_url: API基础URL
        
    Returns:
        Dict: 健康检查结果
    """
    health_result = {
        "healthy": False,
        "checks": {},
        "errors": []
    }
    
    try:
        # 1. 检查基础健康接口
        logger.info("检查基础健康接口...")
        response = requests.get(f"{base_url}/api/health", timeout=10)
        
        if response.status_code == 200:
            health_data = response.json()
            health_result["checks"]["basic_health"] = {
                "status": "pass",
                "response_time": response.elapsed.total_seconds(),
                "data": health_data
            }
            logger.info("✓ 基础健康检查通过")
        else:
            health_result["checks"]["basic_health"] = {
                "status": "fail",
                "error": f"HTTP {response.status_code}"
            }
            health_result["errors"].append(f"基础健康检查失败: HTTP {response.status_code}")
            logger.error(f"✗ 基础健康检查失败: HTTP {response.status_code}")
            
    except requests.exceptions.RequestException as e:
        health_result["checks"]["basic_health"] = {
            "status": "fail",
            "error": str(e)
        }
        health_result["errors"].append(f"基础健康检查异常: {str(e)}")
        logger.error(f"✗ 基础健康检查异常: {str(e)}")
    
    # 2. 检查营业执照识别错误处理
    try:
        logger.info("检查营业执照识别错误处理...")
        
        # 测试营业执照URL接口的错误处理机制
        # 使用不存在的域名来触发网络错误，验证错误处理是否正常工作
        test_data = {"url": "https://nonexistent-domain-12345.com/nonexistent.jpg"}
        response = requests.post(
            f"{base_url}/api/business_license/url",
            json=test_data,
            timeout=30
        )
        
        if response.status_code in [400, 500]:  # 期望的错误状态码
            error_data = response.json()
            if "error_type" in error_data and not error_data.get("success", True):
                health_result["checks"]["error_handling"] = {
                    "status": "pass",
                    "response_time": response.elapsed.total_seconds(),
                    "error_type": error_data.get("error_type"),
                    "message": "错误处理机制正常工作"
                }
                logger.info("✓ 营业执照识别错误处理检查通过")
            else:
                health_result["checks"]["error_handling"] = {
                    "status": "fail",
                    "error": "错误响应格式不正确"
                }
                health_result["errors"].append("错误处理响应格式不正确")
                logger.error("✗ 错误处理响应格式不正确")
        else:
            health_result["checks"]["error_handling"] = {
                "status": "fail",
                "error": f"意外的响应状态码: {response.status_code}"
            }
            health_result["errors"].append(f"错误处理检查失败: HTTP {response.status_code}")
            logger.error(f"✗ 错误处理检查失败: HTTP {response.status_code}")
            
    except requests.exceptions.RequestException as e:
        health_result["checks"]["error_handling"] = {
            "status": "fail",
            "error": str(e)
        }
        health_result["errors"].append(f"错误处理检查异常: {str(e)}")
        logger.error(f"✗ 错误处理检查异常: {str(e)}")
    
    # 3. 检查日志记录功能
    try:
        logger.info("检查日志记录功能...")
        
        # 发送一个会产生日志的请求
        response = requests.post(
            f"{base_url}/api/business_license/upload",
            files={},  # 空文件，会触发错误和日志记录
            timeout=10
        )
        
        # 不管响应如何，只要服务能响应就说明日志记录功能正常
        health_result["checks"]["logging"] = {
            "status": "pass",
            "response_time": response.elapsed.total_seconds(),
            "message": "日志记录功能正常"
        }
        logger.info("✓ 日志记录功能检查通过")
        
    except requests.exceptions.RequestException as e:
        health_result["checks"]["logging"] = {
            "status": "fail",
            "error": str(e)
        }
        health_result["errors"].append(f"日志记录检查异常: {str(e)}")
        logger.error(f"✗ 日志记录检查异常: {str(e)}")
    
    # 4. 检查临时文件管理
    try:
        logger.info("检查临时文件管理...")
        
        # 测试营业执照识别的临时文件管理功能
        # 使用会返回404的URL来触发下载失败，验证临时文件是否正确清理
        test_data = {"url": "https://httpbin.org/status/404"}  # 会触发下载失败，但会创建临时文件
        response = requests.post(
            f"{base_url}/api/business_license/url",
            json=test_data,
            timeout=30
        )
        
        # 不管成功失败，只要有响应就说明临时文件管理正常
        health_result["checks"]["temp_file_management"] = {
            "status": "pass",
            "response_time": response.elapsed.total_seconds(),
            "message": "临时文件管理功能正常"
        }
        logger.info("✓ 临时文件管理检查通过")
        
    except requests.exceptions.RequestException as e:
        health_result["checks"]["temp_file_management"] = {
            "status": "fail",
            "error": str(e)
        }
        health_result["errors"].append(f"临时文件管理检查异常: {str(e)}")
        logger.error(f"✗ 临时文件管理检查异常: {str(e)}")
    
    # 计算总体健康状态
    passed_checks = sum(1 for check in health_result["checks"].values() if check["status"] == "pass")
    total_checks = len(health_result["checks"])
    
    health_result["healthy"] = passed_checks == total_checks
    health_result["summary"] = {
        "passed_checks": passed_checks,
        "total_checks": total_checks,
        "success_rate": (passed_checks / total_checks * 100) if total_checks > 0 else 0
    }
    
    return health_result


def main():
    """主函数"""
    import argparse
    
    parser = argparse.ArgumentParser(description="OCR API健康检查")
    parser.add_argument("--url", default="http://localhost:8002", help="API基础URL")
    parser.add_argument("--timeout", type=int, default=60, help="总超时时间（秒）")
    parser.add_argument("--json", action="store_true", help="输出JSON格式结果")
    
    args = parser.parse_args()
    
    logger.info(f"开始健康检查: {args.url}")
    logger.info("=" * 50)
    
    start_time = time.time()
    
    try:
        health_result = check_api_health(args.url)
        
        elapsed_time = time.time() - start_time
        health_result["check_duration"] = elapsed_time
        
        if args.json:
            print(json.dumps(health_result, indent=2, ensure_ascii=False))
        else:
            print("\n" + "=" * 50)
            print("健康检查结果:")
            print(f"总体状态: {'健康' if health_result['healthy'] else '不健康'}")
            print(f"检查耗时: {elapsed_time:.2f}秒")
            print(f"通过检查: {health_result['summary']['passed_checks']}/{health_result['summary']['total_checks']}")
            print(f"成功率: {health_result['summary']['success_rate']:.1f}%")
            
            if health_result["errors"]:
                print("\n错误信息:")
                for error in health_result["errors"]:
                    print(f"  - {error}")
            
            print("\n详细检查结果:")
            for check_name, check_result in health_result["checks"].items():
                status_icon = "✓" if check_result["status"] == "pass" else "✗"
                print(f"  {status_icon} {check_name}: {check_result['status']}")
                if check_result["status"] == "fail" and "error" in check_result:
                    print(f"    错误: {check_result['error']}")
        
        # 根据健康状态设置退出码
        sys.exit(0 if health_result["healthy"] else 1)
        
    except KeyboardInterrupt:
        logger.info("健康检查被用户中断")
        sys.exit(130)
    except Exception as e:
        logger.error(f"健康检查发生异常: {str(e)}")
        if args.json:
            error_result = {
                "healthy": False,
                "error": str(e),
                "check_duration": time.time() - start_time
            }
            print(json.dumps(error_result, indent=2, ensure_ascii=False))
        sys.exit(1)


if __name__ == "__main__":
    main()